#include <iostream>
#include <memory>

#include "Reactor.hpp"
#include "Connection.hpp"
#include "Listener.hpp"
#include "Log.hpp"
#include "Protocol.hpp"
#include "NetCol.hpp"

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        std::cout << argv[0] << " port" << std::endl;
        exit(USERAGE_ERR);
    }

    LogModule::ConsoleLogStrategy();//将日志打印到显示器上
    uint32_t port = std::stoi(argv[1]);

    std::shared_ptr<NetCol> cal = std::make_shared<NetCol>();//构建业务模块
    std::shared_ptr<Protocol> protocol = std::make_shared<Protocol>(
        [&cal](Request& req) -> Response{
            return cal->Excute(req);
        }
    );
    
    std::shared_ptr<Connection> conn = std::make_shared<Listener>(port);//构建连接
    conn->SetFunction([&protocol](std::string &inbuffer) -> std::string { // 这个匿名函数就是要被Channel
        LOG(LogLevel::DEBUG) << "进入到匿名函数中...";
        std::string response_str;
        while (true)
        {
            std::string package;
            if (!protocol->Decode(inbuffer, &package))
                break;
            // 我敢保证，我的packge一定是一个完整的请求，是字节流的
            response_str += protocol->Execute(package);
        }
        LOG(LogLevel::DEBUG) << "结束匿名函数中...: " << response_str;
        return response_str;
    });

    std::unique_ptr<Reactor> s = std::make_unique<Reactor>();//构建容器
    s->AddConnection(conn);//将连接绑定到容器和内核
    s->Loop();
    return 0;
}